import javax.servlet.http.*;
import java.io.*;
import java.net.*;

//
//
// CounterServlet
//
// Description :
//		
//		Server-Side-Include servlet, tracking page hitcounts
//
// Written by    : David Reilly
// Last modified : June 05, 1998
// 
//
public class CounterServlet extends HttpServlet
{
	public void service ( HttpServletRequest request, HttpServletResponse response ) throws IOException
	{
		doGet(request, response);
	}

	public void doGet ( HttpServletRequest request, HttpServletResponse response ) throws IOException
	{
		// Obtain an output writer for printing information
		PrintWriter out = response.getWriter();

		// Get request url
		StringBuffer requestUrl = HttpUtils.getRequestURL ( request );
		
		// Get request path
		String requestPath;

		try
		{
			// Convert to url
			URL url = new URL (requestUrl.toString());

			// Get path
			requestPath = url.getFile();
		}
		// Was the url invalid
		catch (MalformedURLException mue)
		{
			out.print ("[ERROR]");
			return;
		}
		
		// Substitute all / characters for .
		requestPath = requestPath.replace('/', '.');
		
		// Get number for the counter
		int num = getNumber(requestPath);

		// Print number to screen
		out.print (num);

		// Increment number
		num++;

		// Write number to disk
		writeNumber(requestPath, num);
		
		out.flush();
	}

	public String getServletInfo()
	{
		return new String ("CounterServlet");
	}

	public void writeNumber(String counter, int number) throws IOException
	{
		FileWriter  fwriter = new FileWriter(counter);
		PrintWriter pwriter = new PrintWriter(fwriter);

		pwriter.println (number);
		fwriter.close();
	}

	public int getNumber(String counter) throws IOException
	{
		try
		{
			FileReader freader = new FileReader(counter);
			BufferedReader breader = new BufferedReader (freader);

			// Read a line
			String line = breader.readLine();

			// Close the file so others can access it
			freader.close();

			Integer integer = new Integer (line);

			return integer.intValue();
		}
		catch (FileNotFoundException fnfe)
		{
			return 0;
		}
	}
}

